package per.hnvcam.searchext.parser.impl;

import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import per.hnvcam.common.Callback;
import per.hnvcam.searchext.parser.TextExtraction;

public class TextExtractionImpl extends DefaultHandler implements TextExtraction {
   private StringBuffer buff;
   private Callback callback;
   private boolean removeSpaces = false;

   public TextExtractionImpl() {
      this(null);
   }

   public TextExtractionImpl(Callback callback) {
      buff = new StringBuffer();
      this.callback = callback;
   }

   public String getText() {
      return buff.toString();
   }

   public void setRemoveSpaces(boolean removeSpaces) {
      this.removeSpaces = removeSpaces;
   }

   public boolean isRemoveSpaces() {
      return removeSpaces;
   }

   public void setCallback(Callback callback) {
      this.callback = callback;
   }

   public void characters(char[] arg0, int arg1, int arg2) throws SAXException {
      String data = new String(arg0, arg1, arg2);
      if (removeSpaces) {
         buff.append(data.replaceAll("\\x0B(\\x0B)+", " "));
      }
      else {
         buff.append(data);
      }
   }

   public void endDocument() throws SAXException {
      if (callback != null) {
         callback.run(this);
      }
   }
}
